package com.walkingfiles.registry

import groovy.xml.MarkupBuilder

class LogItem {

    static belongsTo = [document:Document]
    Date date
    User user
    Area area
    String xml
    
    static constraints = {
        xml(maxSize:4095)
    }
    
    private static addLog(document, username, message, area=null) {
        def user = User.findByUsername(username)
        def writer = new StringWriter()
        def xml = new MarkupBuilder(writer)
        xml.p(message)
		if (!area) {
			area = document.currentArea
		}
        def logItem = new LogItem(document: document,
                                  date: new Date(),
                                  user: user,
                                  area: area,
                                  xml: writer.toString())
        logItem.save()

	document.modifiedDate = logItem.date
	document.save(flush:true)
    }
    
    static documentCreated(document, username) {
        addLog(document, username, String.format("Expediente creado"))
    }    

    static documentAttached(document, username, transfer) {
        addLog(document, username, String.format("Expediente agregado a la transferencia: %s", transfer.subject))
    }

    static transferAccepted(document, username, area) {
        addLog(document, username, "Expediente aceptado en la transferencia", area)
    }
	
	static transferRefused(document, username, area) {
		addLog(document, username, "Expediente rechazado en la transferencia", area)
	}
    
    static fileAttached(file, username) {
        addLog(file.document, username, String.format("Documento agregado al expediente: %s", file.toString()))
    }

	static mapping = {
		table 'LogItems'
	}
}
